'use strict';
const dayjs = require("dayjs");
module.exports = app => {
  const { STRING, INTEGER, TEXT,DECIMAL } = app.Sequelize;
    const Model = app.model.define(
      'goods',
      {
          id: {type: INTEGER, primaryKey: true, autoIncrement: true},
          category_id: INTEGER(11),
          name: STRING(255),
          desc: STRING(255),
          status: INTEGER(11),
          company_price: DECIMAL(10, 2),
          price: DECIMAL(10, 2),
          spec: TEXT,
          sale_count: INTEGER(11),
          remark: {
              type: TEXT,
              get() {
                  // 截取img替换img标签中的src属性为服务器地址 .replace('/public/uploads/file/', `${this.$baseUrl}/public/uploads/file/`)
                    return this.getDataValue('remark') ? this.getDataValue('remark').replace(/<img src="/g, `<img src="${app.config.serverUrl}`) : null;
              }
          },
          image: {
              type: STRING(255),
              get() {
                  // 返回拼接当前服务器路径
                  if (this.getDataValue('image') && this.getDataValue('image').indexOf('http') === -1) {
                      return app.config.serverUrl + this.getDataValue('image')
                  }else {
                        return this.getDataValue('image')
                  }
              }
          },

          create_time: {
              type: app.Sequelize.DATE,
              allowNull: false,
              get() {
                  return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
              },
          },
          updated_time: {
              type: app.Sequelize.DATE,
              allowNull: false,
              get() {
                  return dayjs(this.getDataValue('updated_time')).format('YYYY-MM-DD HH:mm:ss');
              },
          }
      },
      {
          tableName: 'goods',
          timestamps: true, // 启用时间戳(createdAt, updatedAt)
          updatedAt: 'updated_time', // 不想要 updatedAt
          createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 created_at
      }
  );

    Model.associate = function () {
        Model.belongsTo(app.model.Category, { foreignKey: 'category_id', targetKey: 'id'})
    }
    return Model
};
